#include "comboboxdelegate.h"

#include <QSet>
#include <QDebug>

ComboBoxDelegate::ComboBoxDelegate(const QStringList &items, QObject *parent, QAbstractItemModel *model, int referenceColumn)
    : QItemDelegate(parent), m_items(items), m_model(model), m_referenceColumn(referenceColumn)
{
}

QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//    qDebug() << "创建下拉框";
    QComboBox *editor = new QComboBox(parent);

    editor->addItems(m_items);  // 初始化下拉框的选项

    QString item = index.data().toString();
//            m_model->index(index).data().toString();
    editor->setCurrentIndex(item.toInt());

//    for (int row = 0; row < m_model->rowCount(); ++row) {
//        QString item = m_model->index(row, m_referenceColumn).data().toString();

//        editor->setCurrentIndex(item.toInt());
//    }

    return editor;
}

void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
    if (comboBox) {
        QString currentValue = index.model()->data(index, Qt::EditRole).toString();

//        qDebug() << currentValue;

//        QString item = currentValue == "1" ? "管理员" : "导员";

//        if(currentValue.count() > 1) {
//            item = currentValue == "管理员" ? "管理员" : "导员";
//        }

        int idx = comboBox->findText(currentValue);
        if (idx != -1) {
            comboBox->setCurrentIndex(idx);  // 设置下拉框当前值
        }
    }
}

void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *comboBox = qobject_cast<QComboBox *>(editor);
    if (comboBox) {
        QString item = comboBox->currentText();
        item = item == "管理员" ? "1" : "0";
        model->setData(index, item, Qt::EditRole);  // 将选择的值保存到模型
    }
}
